angular.module('utils', [])

.directive 'focusMe', ->
    link: (scope, element, attrs) ->
        scope.$watch attrs.focusMe, (value) ->
            if value == true then _.defer ->
                element[0].focus()
                scope[attrs.focusMe] = false

.factory '$localStorage', ->
    set: (key, value) -> window.localStorage?[key] = JSON.stringify(value)
    get: (key)        -> JSON.parse(window.localStorage?[key] || null)

.service 'userData', ($localStorage) ->
    getToken: -> $localStorage.get 'token'
    setToken: (token) -> $localStorage.set 'token', token
    reset: ->
        $localStorage.set 'user', null
        $localStorage.set 'token', null
    get  : -> angular.copy $localStorage.get 'user'
    set  : (user) ->
        $localStorage.set 'user', user
.service 'orderInfo', ()->
    order:undefined
    status:''
    orderStatusIndex:0

.service 'orderPurchase', ()->
    order:undefined
    status:''
    orderStatusIndex:0

.service 'areaData', ()->
    cityList:[]
    provinceList:[]
    city:undefined
    province:undefined

.service 'mallInfo', ()->
    mall:
        logo:undefined
        bannerimg:undefined 

.service 'goodsInfo', ()->
    goods:undefined
    isOnLine:undefined


.service 'newAddress', () ->
    emptyObj =
        name      : undefined
        tel       : undefined
        detail    : undefined
        isDefault : false
        province : {code:'', name:''}
        city     : {code:'', name:''}
        region   : {code:'', name:''}

    address: angular.copy emptyObj
    setData: (obj) ->
        _.extend @address,
            name: obj.name
            tel: obj.phone
            detail: obj.address
            isDefault: obj.isDefault
            province: {code: obj.provinceCode, name: obj.province}
            city: {code: obj.cityCode, name: obj.city}
            region: {code: obj.districtCode, name: obj.district}
    genFormObj: ->
        region : @address.province.name+' '+@address.city.name+' '+@address.region.name+' '
        name   : @address.name
        tel    : @address.tel
        detail : @address.detail
        isDefault: @address.isDefault
    genPostObj: ->
        address      : @address.detail
        phone        : @address.tel
        provinceCode : @address.province.code
        cityCode     : @address.city.code
        districtCode : @address.region.code
        name         : @address.name
        isDefault    : @address.isDefault
#        province     : @address.province.name # TODO 后端应忽略后面这三个参数
#        city         : @address.city.name     # TODO 这三个参数是为了在mock环境
#        district     : @address.region.name   # TODO 能够看到对region的修改
    clear: ->
        @address = angular.copy emptyObj
    isEmpty: -> _.isEqual @address, emptyObj

.service 'wfCache', ->
    mm: {}
    set: (k, v) -> this.mm[k] = v
    get: (k) -> this.mm[k]

.filter 'integer', ->
    (number) ->
        Math.floor number # 获取整数部分

.filter 'decimal', ->
    (number) ->
        # 获取小数部分，保留俩位小数数字
        decimal = (number - Math.floor(number)).toPrecision(3)
        decimal.substr(2)

.service 'wxJsApi', ($http)->
    jsConfig = (js_appId, js_timestamp, js_nonceStr, js_signature) ->
        wx.config({
                debug: false,
                appId: js_appId,
                timestamp: js_timestamp,
                nonceStr: js_nonceStr,
                signature: js_signature,
                jsApiList: ['chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo']
            }
        )

    jsPay = (pay_prepay_id, pay_timestamp, pay_nonceStr, pay_paySign) ->
        #todo 加上loading
        wx.chooseWXPay({
                #开始支付
                timestamp: pay_timestamp,
                nonceStr: pay_nonceStr,
                package: 'prepay_id=' + pay_prepay_id,
                signType: 'MD5',
                paySign: pay_paySign,
                success: (res) ->
                    console.log res
                    $state.go 'tab.orders', {reload: true}

                #todo 微信支付成功代码
                #todo 去掉loading
                fail: (res) ->
                    console.log res
                    alert '支付失败'
                #todo 微信支付失败代码
                cancel: (res) ->
                    console.log res
                    alert '交易被取消'
            }
        )

    jsShare = (title, link, imgUrl, desc, type='link', dataUrl = '') ->
        wx.onMenuShareTimeline({
                title: title
                link: link
                imgUrl: imgUrl
                success: ->
                cancel: ->
            }
        )

        wx.onMenuShareAppMessage({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                type: type, # 分享类型,music、video或link，不填默认为link
                dataUrl: dataUrl, # 如果type是music或video，则要提供数据链接，默认为空
                success: ->
                cancel: ->
            }
        )

        wx.onMenuShareQQ({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                success: ->
                cancel: ->
            }
        )

        wx.onMenuShareWeibo({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                success: ->
                cancel: ->
            }
        )


    pay = (appId,prepay_id, timeStamp,nonceStr,paySign ) ->
        onBridgeReady = ->
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": appId,
                    "timeStamp": timeStamp,
                    "nonceStr": nonceStr,
                    "package": "prepay_id="+prepay_id,
                    "signType": "MD5",
                    "paySign": paySign
                },
                (res) ->
                    if res.err_msg == "get_brand_wcpay_request:ok"
                    else
            )

        if typeof WeixinJSBridge == "undefined"
            if document.addEventListener
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
            else if document.attachEvent
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
        else
            onBridgeReady()

    doConfig = (configSucess = angular.noop,
                configFail = angular.noop)->
        $http.post('/wechat/config', {url: location.href.split('#')[0]})#请求url签名
        .success (resp) ->
            if resp.status == 0
                jsConfig(resp.body.appId, resp.body.timestamp, resp.body.nonceStr, resp.body.signature)
                configSucess()
            else
                configFail()
        .error ->
            configFail()
#    #在程序加载的时候加入这个调用方法,会执行config动作,并且会拦截share动作,微信\朋友圈\qq\tx微博
#    doConfig(
#        ->
#          wx.ready(
#            ->
#              #标题,访问链接,分享的缩略图,分享的描述
#              title = '悦管家'
#              url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc80afb9a921f675a&redirect_uri=http%3A%2F%2Fwechat.yueguanjia.com%2Fjielin-web%2Fwechat%2Flogin&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
#              img = 'http://wechat.yueguanjia.com/jielin-web/img/jl-logo.png'
#              desc = '悦管家'
#              jsShare(title, url, img, desc)
#          )
#        ->
#            console.log 'fail'
#    )

.factory 'guid', ($localStorage) ->
    guid = $localStorage.get 'wf-guid'
    if _.isEmpty(guid)
        guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
            r = Math.random()*16|0
            v = if c == 'x' then r else (r&0x3|0x8)
            v.toString(16)
        $localStorage.set 'wf-guid', guid
    guid

